/* global window */
/* global document */
/* global location */
/* eslint no-restricted-globals: ["error", "event"] */

import { routerRedux } from 'dva/router'
import { parse } from 'qs'
import { config } from 'setting'
// import { query, logout } from 'services/app'
import { logout } from 'services/app'
import * as menusService from 'services/menus'
import queryString from 'query-string'
import pathToRegexp from 'path-to-regexp'

const { prefix, defaultPage } = config

export default {
  namespace: 'app',
  state: {
    user: {},
    // 权限角色（visit 可访问菜单id集合）
    permissions: {
      visit: [],
    },
    isNavbar: document.body.clientWidth < 769,   //是否为小屏
    headerMenus: [],  //头部菜单
    menuPopoverVisible: false,
    menu: [],         //侧边主菜单
    siderFold: window.localStorage.getItem(`${prefix}siderFold`) === 'true',  //侧边主菜单是否折叠
    navOpenKeys: JSON.parse(window.localStorage.getItem(`${prefix}navOpenKeys`)) || [],  //侧边主菜单展开值
    locationPathname: '',
    locationQuery: {},
    language: `zh_CN`,
    hasBread: false,     //面包屑是否显示
    spreadAbled: window.localStorage.getItem(`${prefix}spreadAbled`) === 'true',  //侧边次级菜单是否可以展开（主菜单选中项有子级数据时才可展开）
    spreadProdMenu: window.localStorage.getItem(`${prefix}spreadProdMenu`) === 'true',  //侧边次级菜单是否展开
    prodMenubarTitle: `接口发布服务`,   //侧边次级菜单标题
    prodMenu: JSON.parse(window.localStorage.getItem(`${prefix}prodMenu`)) || [],       //侧边次级菜单
    prodNavOpenKeys: JSON.parse(window.localStorage.getItem(`${prefix}prodNavOpenKeys`)) || [],   //侧边次级菜单展开值
  },
  subscriptions: {
    setupHistory ({ dispatch, history }) {
      history.listen((location) => {
        dispatch({
          type: 'updateState',
          payload: {
            locationPathname: location.pathname,
            locationQuery: location.query,
          },
        })
        dispatch({ type: 'changeBread' })
        // if(location.pathname === defaultPage) dispatch({ type: 'changeBread' })
      })
    },

    setup ({ dispatch }) {
      window.localStorage.removeItem(`${prefix}lastMenuType`)  //*清除最后一次菜单执行方式
      dispatch({ type: 'query' })
      let tid
      window.onresize = () => {
        clearTimeout(tid)
        tid = setTimeout(() => {
          dispatch({ type: 'changeNavbar' })
        }, 300)
      }
    },

    setupLang ({ dispatch }){
      const language = window.localStorage.getItem(`${prefix}language`)
      if(language && language !== 'undefined' && language !== 'null'){
        dispatch({ type: 'handleLang', payload: language })
      } else {
        dispatch({ type: 'handleLang', payload: `zh_CN` })
      }
    },

  },
  effects: {

    *query (action, { call, put, select }) {
      // const { success, user } = yield call(query, payload)
      // console.log(payload)   
      const { success, user } = {
        success: true,
        user: {"permissions":{ "role": "admin" },"username":"admin","id": 1 },
      }
      const { locationPathname } = yield select(_ => _.app)
      if (success && user) {
        const headerResult = yield call(menusService.queryHeaderMenus)
        const menusResult = yield call(menusService.queryMenus)

        let headerMenus = headerResult.list
        let menu = menusResult.list
        const { permissions } = user
        if (permissions.role === "admin" || permissions.role === 'developer') {
          permissions.visit = menusResult.list.map(item => item.id)
        } else {
          menu = menusResult.list.filter((item) => {
            const cases = [
              permissions.visit.includes(item.id),   //该菜单id是否在可访问菜单中存在
              // mpid不存在 || mpid在可访问菜单list中存在 || mpid为-1
              item.mpid ? permissions.visit.includes(item.mpid) || item.mpid === '-1' : true,
            ]
            return cases.every(_ => _)
          })
        }
        yield put({
          type: 'updateState',
          payload: {
            user,
            permissions,
            menu,
            headerMenus,
          },
        })

        if (location.pathname === '/login') {
          yield put(routerRedux.push({
            pathname: defaultPage,
          }))
        }
      } else if (config.openPages && config.openPages.indexOf(locationPathname) < 0) {
        yield put(routerRedux.push({
          pathname: '/login',
          search: queryString.stringify({
            from: locationPathname,
          }),
        }))
      }
    },

    *logout ({
      payload,
    }, { call, put }) {
      const data = yield call(logout, parse(payload))
      if (data.success) {
        yield put({ type: 'updateState', payload: {
          user: {},
          permissions: { visit: [] },
          menu: [],
        }})
        yield put({ type: 'query' })
      } else {
        throw (data)
      }
    },

    // 响应式切换侧边主菜单
    *changeNavbar (action, { put, select }) {
      const { app } = yield (select(_ => _))
      const isNavbar = document.body.clientWidth < 769
      if (isNavbar !== app.isNavbar) {
        yield put({ type: 'handleNavbar', payload: isNavbar })
      }
    },

    // 获取并展开prodMenu
    *getProdMenu ({ payload }, { call, put, select }){
      const { list } = yield call(menusService.queryProdMenus, payload)
      const { spreadProdMenu } = yield (select( _ => _.app ))
      if( list.length && spreadProdMenu === false ) yield put({ type: 'switchProdMenu' })
      window.localStorage.setItem(`${prefix}prodMenu`, JSON.stringify(list))
      yield put({
        type: 'updateState',
        payload: { prodMenu: list },
      })
    },

    // 切换面包屑
    *changeBread (action, { put, select }){
      const { app } = yield (select(_ => _))
      let isBread = false
      const RegexpPathname = app.prodMenu.filter(item => pathToRegexp(item.link_to || '').exec(location.pathname))
      if(RegexpPathname.length>0){
        isBread = false
      } else {
        if(app.prodMenu){
          app.prodMenu.find((value) => {
            if((location.pathname).includes(value.link_to) || ( value.link_to && (value.link_to).includes(location.pathname) )) isBread = true
            return false
          })
        }
      }

      yield put({ type: 'switchBread', payload: isBread })
    },

  },
  reducers: {
    // 更新数据
    updateState (state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },
    switchMenuPopover (state) {
      return {
        ...state,
        menuPopoverVisible: !state.menuPopoverVisible,
      }
    },

    handleNavbar (state, { payload }) {
      return {
        ...state,
        isNavbar: payload,
      }
    },
    // 更新 主菜单折叠状态
    switchSider (state) {
      window.localStorage.setItem(`${prefix}siderFold`, !state.siderFold)
      return {
        ...state,
        siderFold: !state.siderFold,
      }
    },
    // 更新 主菜单展开值
    handleNavOpenKeys (state, { payload: navOpenKeys }) {
      return {
        ...state,
        ...navOpenKeys,
      }
    },
    // 更新 次级菜单展开能力
    switchSpreadAbled (state, { payload: spreadAbled }) {
      window.localStorage.setItem(`${prefix}spreadAbled`, spreadAbled)
      return {
        ...state,
        spreadAbled,
      }
    },
    // 更新 次级菜单面板展开状态
    switchProdMenu (state) {
      window.localStorage.setItem(`${prefix}spreadProdMenu`, !state.spreadProdMenu)
      return {
        ...state,
        spreadProdMenu: !state.spreadProdMenu,
      }
    },
    // 更新 次级菜单展开值
    handleProdNavOpenKeys (state, { payload: prodNavOpenKeys }) {
      return {
        ...state,
        ...prodNavOpenKeys,
      }
    },
    // 更新面包屑状态
    switchBread (state, { payload }){
      return {
        ...state,
        hasBread: payload,
      }
    },
    // 更新国际化语言
    handleLang (state, { payload }) {
      return {
        ...state,
        language: payload,
      }
    },
  },
}
